package logic

import (
	"context"
	"errors"
	"user_srv/models/mysql"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealNameLogic) RealName(in *user.RealNameRequest) (*user.RealNameResponse, error) {
	// todo: add your logic here and delete this line

	//用户是否已实名认证 实名认证信息是否已被注册
	ur := mysql.RealName{}
	err := ur.GetByUserIdOrIdCard(int(in.UserId), in.IdCard)
	if err != nil {
		return nil, errors.New("实名信息查询失败")
	}
	if ur.ID != 0 {
		logx.Error("实名信息已被注册")
		return nil, errors.New("实名信息已被注册")
	}
	if !pkg.RealName(in.IdCard, in.RealName) {
		return nil, errors.New("实名认证失败")
	}
	logx.Info("实名认证成功")
	ur.UserId = int(in.UserId)
	ur.IdCard = in.IdCard
	ur.RealName = in.RealName
	err = ur.Add()
	if err != nil {
		return nil, errors.New("实名信息保存失败")
	}

	return &user.RealNameResponse{RealName: ur.RealName}, nil
}
